<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="stepActive - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="goodsForm" :rules="goodsFormRules" ref="goodsFormRef" label-width="100px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="stepActive" :before-leave="TagBeforeLeave" @tab-click="TabsClickd">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="goodsForm.goods_cat" :options="AllCateList" :props="cateProps"
                @change="cateHandleChange" clearable>
              </el-cascader>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item) in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="v" border v-for="(v,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item) in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="upload-demo" :action="uploadUrl" :on-preview="pichandlePreview"
              :on-remove="pichandleRemove" list-type="picture" :headers="uploadHeaders" :on-success="pichandleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGood" class="addGoodBut">完成</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览框 -->
      <el-dialog title="图片预览" :visible.sync="previewVisible" width="40%">
        <img :src="previewPath" alt="" srcset="" class="previewImg">
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stepActive: '0',
      //商品form表单数据对象
      goodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //商品分类
        goods_cat: [],
        //商品图片
        pics: [],
        //商品的参数
        attrs: [],
        goods_introduce: '',
      },
      //表单验证规则
      goodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },

      AllCateList: [],
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      //商品参数数据
      manyTabData: [],
      //商品属性数据
      onlyTabData: [],

      //图片上传地址
      uploadUrl: 'http://192.168.131.136:8888/api/private/v1/upload',
      //图片上传请求头
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token'),
      },
      previewVisible: false,
      //图片预览路径
      previewPath: '',
    }
  },
  methods: {
    async getCateData() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法获取商品分类数据')
      }
      this.AllCateList = res.data
    },

    cateHandleChange() {
      console.log(this.goodsForm.goods_cat)
    },

    TagBeforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.goodsForm.goods_cat.length !== 3) {
        this.$message.warning('请先选着商品分类')
        return false
      }
    },
    //切换tabs标签时触发
    async TabsClickd() {
      console.log(this.stepActive)
      if (this.stepActive === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('请求服务器失败，无法获取商品参数信息！')
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTabData = res.data
      } else if (this.stepActive === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('请求服务器失败，无法获取商品属性信息！')
        }
        this.onlyTabData = res.data
      }
    },
    //图片预览行为
    pichandlePreview(file) {
      // console.log(file)
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    //图片删除
    pichandleRemove(file) {
      // console.log(file)
      const picInfo = file.response.data.tmp_path
      //从pics数组中移除图片对象
      const fileInd = this.goodsForm.pics.findIndex((f) => {
        return f.pic === picInfo
      })
      this.goodsForm.pics.splice(fileInd, 1)
    },
    //图片上传成功
    pichandleSuccess(response) {
      console.log(response)
      //得到每张图片的临时路径
      const picInfo = response.data.tmp_path
      //push到pics中
      this.goodsForm.pics.push(picInfo)
    },
    //添加商品请求
    addGood() {
      this.$refs.goodsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.warning('请填写必填项！')
        }
        //goods_cat数据处理
        this.goodsForm.goods_cat = this.goodsForm.goods_cat.join(',')
        //参数
        this.manyTabData.forEach((item) => {
          const manyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.goodsForm.attrs.push(manyInfo)
        })
        //属性
        this.onlyTabData.forEach(item => {
          const onlyInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.goodsForm.attrs.push(onlyInfo)
        })
        console.log(this.goodsForm)
        const {data: res} = await this.$http.post('goods',this.goodsForm)
        if(res.meta.status !== 201){
          return this.$message.error("请求服务器失败，无法添加商品信息！")
        }
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.goodsForm.goods_cat.length === 3) {
        return this.goodsForm.goods_cat[2]
      }
      return null
    },
  },
  created() {
    this.getCateData()
  },
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 5px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addGoodBut {
  margin-top: 15px;
}
</style>